-- matcher.lua 坦克配对

local M = { }

local log = require("log"):new("tanks.matcher")
local Player = require("tanks.player")
local user_mgr = require("user_mgr")
local room_mgr = require("tanks.room_mgr")

-- 第一个请求者game_clt_id，nil表示无
local first_one

-- 开房间
local function match_player(second_one)
    log:info("match_player")

    local first = first_one
    local second = second_one
    first_one = nil
    -- always reset

    assert(first)
    assert(second)
    log:debug("match_player: %s %s", first:to_string(), second:to_string())
    local account1 = user_mgr.get_user_account(first.base_rpc_clt_id)
    assert(account1)
    local account2 = user_mgr.get_user_account(second.base_rpc_clt_id)
    assert(account2)
    log:debug("match_player %s vs %s", account1, account2)
    player1 = Player:new(first, account1)
    player2 = Player:new(second, account2)
    room_mgr.enter(player1, player2)
end  -- match_player()

-- 请求匹配
function M.enter(game_clt_id)
    log:debug("enter")
    assert(game_clt_id)
    if not first_one then
        first_one = game_clt_id
        log:debug("Enter Match: clt.%s", first_one:to_string())
        return
    end
    if first_one:equals(game_clt_id) then
        return
    end
    local account1 = user_mgr.get_user_account(first_one.base_rpc_clt_id)
    if not account1 then
        -- first_one is offline.
        first_one = game_clt_id
        -- 重新等待下一位
        return
    end

    match_player(game_clt_id)
end  -- enter()

-- 退出匹配
function M.exit(game_clt_id)
    assert(game_clt_id)
    log:debug("Exit match: clt.%s", game_clt_id:to_string())
    if not first_one then return end
    if game_clt_id:equals(first_one) then
        first_one = nil
    end
end  -- exit()

return M
